package com.lksoft.bz;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;

/**
 * Bead database
 * 
 * @author Lake
 *
 */
public class BeadDB {
	
	private static BeadDB self = new BeadDB();
	public static BeadDB get()  { return self; }

	/** Stitch data to Bead */
	private LinkedHashMap<Integer, Bead> beadDB = new LinkedHashMap<>();
	
	/**
	 * Add a bead to the database
	 * @param bead
	 */
	public void addBead(Bead bead){
		beadDB.put(bead.getColor(), bead);
	}
	
	/**
	 * Gets a bead from its stitch representation
	 * @param stitchData
	 * @return 
	 */
	public Bead getBead(int stitchData){
		return beadDB.get(stitchData);
	}
	
	/**
	 * @return Bead list
	 */
	public LinkedHashMap<Integer, Bead> getBeadMap() {
		return beadDB;
	}
	
	/**
	 * Save database to specified file (overrides)
	 * @param path
	 * @throws IOException 
	 */
	public void saveToFile(String path) throws IOException{
		
		// Open file
		File file = new File(path);
		file.createNewFile();
		
		FileWriter fw = new FileWriter(file);
		
		for( Bead bead : beadDB.values() ){
			fw.write(bead.toString() + "\n");
		}
		
		fw.close();
	}
	
	public void openFile(String path) throws IOException{
		// Open file	
		BufferedReader fr = new BufferedReader(new InputStreamReader(Bz.class.getResourceAsStream(path)));
		
		while(true){
			String line = fr.readLine();
			if( line == null ) break;
			
			Bead bead = new Bead(line);
			addBead(bead);
		}
		
		fr.close();
	}

}
